package com.eg366.nioLearn.baseSocket.chapter02.TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class TCPEchoServer {
	
	public static final int BUFSIZE = 32;
	
	public static void main(String[] args) throws IOException {
		args = new String[]{"1122"};
		if(args.length != 1) {
			throw new IllegalArgumentException("Parameter(s):<Port>");
		}
		
		/* 服务器端端口号 */
		int servPoint = Integer.parseInt(args[0]);
		
		/* 建立服务器端监听套接字 */
		ServerSocket servSock = new ServerSocket(servPoint);
		
		int recvMsgSize;
		byte[] receiveBuf = new byte[BUFSIZE];
		
		while(true) {
			/* 为每个连接创建一个新的套接字;阻塞 */
			Socket clntSock = servSock.accept();
			
			/* 已连接客户端的地址 */
			SocketAddress clientAddress = clntSock.getRemoteSocketAddress();
			/* 打印的是IP+端口（SocketAddress）信息，InetAddress是IP信息 */
			System.out.println("Handling client at " + clientAddress);
			
			InputStream in = clntSock.getInputStream();
			OutputStream out = clntSock.getOutputStream();
			
			while((recvMsgSize = in.read(receiveBuf)) != -1) {
				out.write(receiveBuf, 0, recvMsgSize);
			}
			clntSock.close();
		}
	}
}
